package org.demo.algorithm.lagou.column.relearn;

import java.util.HashMap;
import java.util.Map;

/**
 * 求出现次数最多的元素
 */
public class CountMax {

    public static Integer count(int[] source) {
        if (source == null || source.length == 0) {
            return Integer.MIN_VALUE;
        }

        Map<Integer, Integer> counter = new HashMap<>();
        for (int value : source) {
            counter.putIfAbsent(value, 0);
            Integer count = counter.get(value);
            counter.put(value, ++count);
        }

        int max = Integer.MIN_VALUE;
        int result = 0;
        for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
            if (entry.getValue() > max) {
                max = entry.getValue();
                result = entry.getKey();
            }
        }
        return result;
    }

}
